<?php
/**
 * @title 313. 超级丑数 - 最小堆
 * @author start2004
 */

class Solution {

    /**
     * @param Integer $n
     * @param Integer[] $primes
     * @return Integer
     */
    function nthSuperUglyNumber($n, $primes) {
        /**
         * @since 2020-07-30 最小堆
         */
        $heap = new SplMinHeap();
        $heap->insert(1);

        /**
         * @since 2020-07-30 去重
         */
        $hashs = [];

        /**
         * @since 2020-07-30 遍历
         */
        while($n > 0){
            /**
             * @since 2020-07-30 移除最小值
             */
            $min = $heap->extract();
            // echo "n={$n}, min={$min}", PHP_EOL;

            /**
             * @since 2020-07-30 加入新的元素, 防止重复
             */
            foreach ($primes as $k){
                $val = $k*$min;
                if(!isset($hashs[$val])){
                    $heap->insert($val);
                    $hashs[$val] = 1;
                } else {}
            }

            $n--;
        }

        /**
         * @return
         */
        return $min;
    }
}




/**
 * @url http://127.0.0.1/leetcode/202007/2020.07.30_4.php
 */
$datas = [
    [12, [2,7,13,19]], // 32
    [12, [2,7,13,19]], // 32
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->nthSuperUglyNumber($data[0], $data[1]);
    var_dump($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
